﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Store;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.Store;
using AMM.UserControls;
using Microsoft.Reporting.WinForms;

namespace AMM.Forms.Store {
    public partial class FrmProductInStoreOrder : FrmProductInStoreOrderBase {

        private int _pageIndex;
        private ProductInStoreOrderSearchModel _searchModel;
        private ProductInStoreOrderProcessor _productInStoreOrderProcessor;
        private List<ProductInStoreOrderViewModel> _productInStoreOrderList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1417"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new ProductInStoreOrderSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new ProductInStoreOrder() { ClassStatus = ClassStatus.Added });
            base.Add();
        }

        protected override void Amend() {
            List<ProductInStoreOrderViewModel> selectedList = this.dgvProductInStoreOrderList.GetSelectedRows<ProductInStoreOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            ProductInStoreOrder productInStoreOrder = this._productInStoreOrderProcessor.FetchProductInStoreOrderById(selectedList[0].Key);
            productInStoreOrder.ClassStatus = ClassStatus.Updated;
            if ((AuditStatus)productInStoreOrder.Status == AuditStatus.Audited) {
                this.ShowInfo("审核的订单不能被修改！");
                return;
            }
            this.ShowEditForm("修改", productInStoreOrder);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Delete() {
            List<ProductInStoreOrderViewModel> selectedList = this.dgvProductInStoreOrderList.GetSelectedRows<ProductInStoreOrderViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._productInStoreOrderProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Delete();
            });
        }

        protected override void Audit() {
            List<ProductInStoreOrderViewModel> selectedList = this.dgvProductInStoreOrderList.GetSelectedRows<ProductInStoreOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                string resultMsg = string.Empty;
                ProductInStoreOrder productInStoreOrder = this._productInStoreOrderProcessor.FetchProductInStoreOrderById(selectedList[0].Key);
                if (productInStoreOrder.Status == (int)AuditStatus.Audited) {
                    this.ShowError("订单已经通过审核，系统已禁止入库单取消审核！");
                    return;
                }
                else {
                    productInStoreOrder.Status = (int)AuditStatus.Audited;
                    resultMsg = "审核成功";
                }
                productInStoreOrder.AuditedBy = LoginUserName;
                this._productInStoreOrderProcessor.Audit(productInStoreOrder);
                this.MDIParent.SetStatusInformation(resultMsg);
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Audit();
            });
        }

        protected override void Print() {
            List<ProductInStoreOrderViewModel> selectedList = this.dgvProductInStoreOrderList.GetSelectedRows<ProductInStoreOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PrintHelperIns = new PrintHelper("ProductInStoreOrderPrint.rdlc", this.Text);
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds", selectedList));
                base.Print();
            }, () => {
                // for hiding
                this.PrintHelperIns.Dispose();
            });
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new ProductInStoreOrderSearchModel();
                }
                else {
                    this._searchModel = (ProductInStoreOrderSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindProductInStoreOrderList();
            });
        }

        #endregion

        public FrmProductInStoreOrder() {
            InitializeComponent();

            this.dgvProductInStoreOrderList.DataGridViewModelType = typeof(ProductInStoreOrderViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            ProductInStoreOrder productInStoreOrder = (ProductInStoreOrder)e.EditModel;
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                if (productInStoreOrder.ClassStatus == ClassStatus.Added) {
                    productInStoreOrder.CreatedBy = LoginUserName;
                    this._productInStoreOrderProcessor.Insert(productInStoreOrder);
                }
                else {
                    productInStoreOrder.ModifiedBy = LoginUserName;
                    this._productInStoreOrderProcessor.Update(productInStoreOrder);
                }
                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });

            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindProductInStoreOrderList();
        }

        private void BindProductInStoreOrderList() {
            this.CreateNewThread(() => {
                this._productInStoreOrderList = this._productInStoreOrderProcessor.FetchProductInStoreOrderViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvProductInStoreOrderList.DataSource = new SortableBindingList<ProductInStoreOrderViewModel>(this._productInStoreOrderList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void ShowEditForm(string title, ProductInStoreOrder productInStoreOrder) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                ProductInStoreOrderEditControl editControl = new ProductInStoreOrderEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = productInStoreOrder;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmProductInStoreOrder_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._productInStoreOrderProcessor = new ProductInStoreOrderProcessor(this.pceList.PageSize);
                this._searchModel = new ProductInStoreOrderSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindProductInStoreOrderList();
        }
    }
}
